#!/usr/bin/env python
# -*- encoding:utf-8 -*-
import os
import config
import myos

class MsgMgr(object):
	def __init__(self, fromp, top):
		self.fromp = os.path.abspath(fromp)
		self.froms = {}
		self.top = os.path.abspath(top)
		self.tos = {}
		pass

	def switch(self):
		for i in config.targets :
			self.init_from(i)
		self.init_to()
		self.cp()

		pass
	
	def cp(self):
		for i in self.froms:
			if i not in self.tos:
				continue
			for j in self.tos[i]:
				#cmd = "cp " + self.froms[i] + " " + j
				#os.system(cmd)
				myos.cp(self.froms[i], j)
				#print(cmd)
		if "Windows" == myos.sys:
			raw_input("press any key to continue ...")
	
	def init_to(self):
		path = self.top
		
		for i in self.froms:
			#cmd = "find " + path + " -name " + i
			#cmd = 'find ' + path + ' -name \"' + i + '\"'
			#f = os.popen(cmd)
			f = myos.find(path, i)
			ps = []
			for j in f:
				j = j.strip(config.space)
				#print(j)
				#print("->>>")
				#print(self.froms[i])
				nstr = os.path.split(j)
				p = nstr[0]
				fpath = os.path.split(self.froms[i])
				if p == fpath[0]:
					continue
				ps.append(p)
			if len(ps) > 0:
				self.tos[i] = ps
			

		pass

	def init_from(self, se):
		path = self.fromp
		#cmd = 'find ' + path + ' -name \"' + se + '\"'

		#f = os.popen(cmd)
		f = myos.find(path, se)
		for i in f:
			i = i.strip(config.space)
			nstr = os.path.split(i)
			#print(nstr)
			name = nstr[1]
			self.froms[name] = i
		pass

def check():
	fromdir = os.path.abspath(config.fromdir)
	todir = os.path.abspath(config.todir)
	if fromdir == todir:
		return False

	if not os.path.exists(fromdir) :
		return False
	if not os.path.exists(todir) :
		return False
	
	if not os.path.isdir(fromdir) :
		return False
	
	if not os.path.isdir(todir) :
		return False

	return True
	pass

if __name__ == '__main__':
	if check():
		mgr = MsgMgr(config.fromdir, config.todir)
		mgr.switch()

